# 导入库
from py_commander import Network
import time
import os
import threading
import platform
import datetime

# 配置信息
PORT = 9999  # 通信端口
MACHINE_B_IP = "192.168.189.128"  # 替换为实际的机器B的IP地址

# 当前机器信息
machine_name = platform.node()
current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print("\n===== 机器A启动 ({0}) =====".format(machine_name))
print("当前时间: {0}".format(current_time))
print("系统信息: {0} {1}".format(platform.system(), platform.release()))

# 创建测试目录
test_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "test_data_A")
if not os.path.exists(test_dir):
    os.makedirs(test_dir)

# 创建测试文件
test_file_path = os.path.join(test_dir, "from_A_to_B.txt")
with open(test_file_path, 'w') as file:
    file.write("这是从机器A发送到机器B的测试文件\n")
    file.write("创建时间: {0}\n".format(current_time))
    file.write("机器名称: {0}\n".format(machine_name))

# 定义消息处理回调函数
def message_handler(data, response, address):
    msg_type = data.get('type')
    if msg_type == 'message':
        print("\n[收到消息] 来自 {0}: {1}".format(address[0], data.get('message')))
    elif msg_type == 'file_transfer':
        print("\n[收到文件] 来自 {0}: 已保存到 {1}".format(address[0], data.get('file_path')))
    elif msg_type == 'execute':
        print("\n[收到命令] 来自 {0}: {1}".format(address[0], data.get('command')))
    elif msg_type == 'ping':
        print("\n[收到Ping] 来自 {0}".format(address[0]))

# 启动服务器
server_thread = Network.start_server(port=PORT, callback=message_handler)
print("服务器已启动在端口 {0}，等待来自机器B的连接...".format(PORT))

# 主循环
try:
    # 菜单系统
    while True:
        print("\n===== 机器A控制面板 =====")
        print("1. 向机器B发送消息")
        print("2. 向机器B发送文件")
        print("3. 在机器B上执行命令")
        print("4. Ping机器B")
        print("5. 异步执行多个操作")
        print("6. 退出")
        
        choice = input("\n请选择操作 (1-6): ").strip()
        
        if choice == '1':
            message = input("请输入要发送的消息: ")
            print("发送消息中...")
            response = Network.send_message(MACHINE_B_IP, message, port=PORT)
            print("消息发送结果: {0}".format(response['status']))
            if response['status'] == 'success':
                print("消息已成功发送到机器B")
            else:
                print("发送失败: {0}".format(response.get('message')))
        
        elif choice == '2':
            print("将发送文件: {0}".format(test_file_path))
            remote_path = input("请输入机器B上的保存路径 (例如 D:/test_data_B/from_A.txt): ")
            print("发送文件中...")
            response = Network.send_file(MACHINE_B_IP, test_file_path, remote_path, port=PORT)
            print("文件传输结果: {0}".format(response['status']))
            if response['status'] == 'success':
                print("文件已成功发送到机器B: {0}".format(remote_path))
            else:
                print("传输失败: {0}".format(response.get('message')))
        
        elif choice == '3':
            command = input("请输入要在机器B上执行的命令: ")
            print("执行命令中...")
            response = Network.send_command(MACHINE_B_IP, command, port=PORT, timeout=30)
            print("命令执行结果: {0}".format(response['status']))
            print("返回值: {0}".format(response.get('return_value')))
            if response['stdout']:
                print("标准输出:\n{0}".format(response['stdout']))
            if response['stderr']:
                print("标准错误:\n{0}".format(response['stderr']))
        
        elif choice == '4':
            print("Ping机器B中...")
            response = Network.ping(MACHINE_B_IP, port=PORT)
            print("Ping结果: {0}".format(response['status']))
            if response['status'] == 'success':
                print("机器B在线!")
                system_info = response.get('system_info', {})
                print("系统信息: {0}".format(system_info.get('platform')))
                print("主机名: {0}".format(system_info.get('node')))
            else:
                print("Ping失败: {0}".format(response.get('message')))
                
        elif choice == '5':
            print("开始异步操作测试...")
            
            # 异步发送消息
            message_future = Network.send_message_async(
                MACHINE_B_IP, 
                "来自机器A的异步消息-{0}".format(current_time), 
                port=PORT,
                callback=lambda r: print("\n异步消息发送完成: {0}".format(r['status']))
            )
            
            # 异步发送文件
            file_future = Network.send_file_async(
                MACHINE_B_IP, 
                test_file_path, 
                "D:/test_data_B/async_from_A_{0}.txt".format(int(time.time())), 
                port=PORT,
                callback=lambda r: print("\n异步文件传输完成: {0}".format(r['status']))
            )
            
            # 异步执行命令
            command_future = Network.send_command_async(
                MACHINE_B_IP, 
                "echo 这是机器A异步执行的命令 & time /t", 
                port=PORT,
                callback=lambda r: print("\n异步命令执行完成: {0}".format(r.get('return_value')))
            )
            
            print("所有异步操作已启动，继续执行主线程...")
            
            # 等待所有操作完成
            for i in range(5):
                print("等待异步操作完成... {0}/5".format(i+1))
                time.sleep(1)
                
            print("\n异步操作结果:")
            try:
                msg_result = message_future.result(timeout=1)
                file_result = file_future.result(timeout=1)
                cmd_result = command_future.result(timeout=1)
                print("所有异步操作已完成!")
            except Exception as e:
                print("获取异步结果时出错: {0}".format(str(e)))
        
        elif choice == '6':
            print("退出程序...")
            break
            
        else:
            print("无效选择，请重新输入.")
            
except KeyboardInterrupt:
    print("\n检测到用户中断，正在退出...")
except Exception as e:
    print("\n发生错误: {0}".format(str(e)))
finally:
    # 清理资源
    print("关闭服务器和清理资源...")
    Network.shutdown()
    print("退出.") 